package com.wrl.mmall.service.impl;

import com.wrl.mmall.common.Const;
import com.wrl.mmall.common.ResponseCode;
import com.wrl.mmall.common.ServerResponse;
import com.wrl.mmall.common.enums.ProductStatusEnum;
import com.wrl.mmall.dao.CategoryMapper;
import com.wrl.mmall.dao.ProductMapper;
import com.wrl.mmall.pojo.Category;
import com.wrl.mmall.pojo.Product;
import com.wrl.mmall.service.ICategoryService;
import com.wrl.mmall.service.IProductService;
import com.wrl.mmall.util.DateTimeUtil;
import com.wrl.mmall.util.PropertiesUtil;
import com.wrl.mmall.vo.ProductDetailVo;
import com.wrl.mmall.vo.ProductListVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("iProductService")
@Slf4j
public class ProductServiceImpl implements IProductService{
	
	@Autowired
	private ProductMapper productMapper;
	@Autowired
	private CategoryMapper categoryMapper;
	@Autowired
	private ICategoryService iCategoryService;

	//前端
	//获取商品详情
	@Override
	public ServerResponse<ProductDetailVo> getProductDetail(Integer productId){
		log.info("saveOrUpdateProduct.getProductDetail");
		if(productId == null) {
			return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
		}
		Product product = productMapper.selectByPrimaryKey(productId);
		if(product == null) {
			return ServerResponse.createByErrorMessage("产品已下架或删除");
		}
		if(product.getStatus() != ProductStatusEnum.ON_SALE.getCode()) {
			return ServerResponse.createByErrorMessage("产品已下架或删除");
		}

		//vo → value object
		ProductDetailVo productDetailVo = assembeProductDetailVo(product);
		return ServerResponse.createBySuccess(productDetailVo);
	}

	//
	@Override
	public ServerResponse<PageInfo> getProductByKeywordCategory(String keyword, Integer categoryId, int pageNum, int pageSize, String orderBy){
		log.info("saveOrUpdateProduct.getProductByKeywordCategory");
		if(StringUtils.isBlank(keyword) && categoryId == null) {
			return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
		}

		List<Integer> categoryIdList = new ArrayList<Integer>();
		if(categoryId != null) {
			Category category = categoryMapper.selectByPrimaryKey(categoryId);
			if(category == null && StringUtils.isBlank(keyword)) {
				//没有该分类，并且还没有关键字，这个时候返回一个空的结果集，不报错
				PageHelper.startPage(pageNum, pageSize);
				List<ProductListVo> productListVos = Lists.newArrayList();
				PageInfo pageInfo = new PageInfo(productListVos);
				return ServerResponse.createBySuccess(pageInfo);
			}
			//递归获取分类
			categoryIdList = iCategoryService.selectCategoryAndChildrenById(categoryId).getData();
		}
		if(!StringUtils.isBlank(keyword)) {
			keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
		}

		//开始分页
		PageHelper.startPage(pageNum, pageSize);
		if(StringUtils.isBlank(orderBy)) {
			if(Const.productListOrderBy.PRICE_ACS_DESC.contains(orderBy)) {
				//通过下划线进行分割
				String[] orderByArray = orderBy.split("_");
				PageHelper.orderBy(orderByArray[0]+" "+orderByArray[1]);
			}

		}
		List<Product> productList = productMapper.selectByNameAndCategoryId(
				StringUtils.isBlank(keyword)? null: keyword,
				categoryIdList.size() == 0 ? null: categoryIdList);
		List<ProductListVo> productListVos = Lists.newArrayList();
		for (Product product : productList) {
			ProductListVo productListVo = assembleProductListVo(product);
			productListVos.add(productListVo);
		}
		PageInfo pageInfo = new PageInfo(productList);
		pageInfo.setList(productListVos);
		return ServerResponse.createBySuccess(pageInfo);
	}


	/* 后端 */
	@Override
	public ServerResponse saveOrUpdateProduct(Product product) {
		log.info("saveOrUpdateProduct.saveOrUpdateProduct");
		if(product != null) {
			//判断是否具有必须的参数
			if(product.getCategoryId() == null || product.getStock() == null || product.getPrice() == null) {
				return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
			}
			if(StringUtils.isNotBlank(product.getSubImages())) {
				//获取图片组
				String[] subImagesArray = product.getSubImages().split(",");
				if(subImagesArray.length > 0) {
					//设置图片组的第一张图为主图
					product.setSubImages(subImagesArray[0]);
				}
			}
			//如果前端输入了id，就是修改;没有输入，就是添加
			if(product.getId() != null) {
				int count = productMapper.updateByPrimaryKey(product);
				if(count > 0) {
					return ServerResponse.createBySuccess("更新产品成功");
				}
				return ServerResponse.createByErrorMessage("更新产品失败");
			}else {
				int count = productMapper.insert(product);
				if(count > 0) {
					return ServerResponse.createBySuccess("添加产品成功");
				}
				return ServerResponse.createByErrorMessage("保存产品失败");
			}
		}
		return ServerResponse.createByErrorMessage("新增或更新产品格式不正确");
	}

	@Override
	public ServerResponse<String> setSaleStatus(Integer productId, Integer status) {
		log.info("saveOrUpdateProduct.setSaleStatus");
		if(productId == null || status == null) {
			return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
		}
		Product product = new Product();
		product.setId(productId);
		product.setStatus(status);
		int rowCount = productMapper.updateByPrimaryKeySelective(product);
		if(rowCount > 0) {
			return ServerResponse.createBySuccess("修改产品销售状态成功");
		}
		return ServerResponse.createByErrorMessage("修改产品销售状态失败");
		
	}
	
	@Override
	public ServerResponse<ProductDetailVo> manageProductDetail(Integer productId) {
		log.info("saveOrUpdateProduct.manageProductDetail");
		if(productId == null) {
			return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
		}

		Product product = productMapper.selectByPrimaryKey(productId);
		if(product == null) {
			return ServerResponse.createByErrorMessage("产品已下架或删除");
		}
		
		//vo对象
		ProductDetailVo productDetailVo = assembeProductDetailVo(product);
		return ServerResponse.createBySuccess(productDetailVo);
	}
	
	//组装vo
	private ProductDetailVo assembeProductDetailVo(Product product) {
		ProductDetailVo detailVo = new ProductDetailVo();
		detailVo.setId(product.getId());
		detailVo.setSubtitle(product.getSubtitle());
		detailVo.setPrice(product.getPrice());
		detailVo.setMainImage(product.getMainImage());
		detailVo.setSubImages(product.getSubImages());
		detailVo.setCatagoryId(product.getCategoryId());
		detailVo.setDetail(product.getDetail());
		detailVo.setName(product.getName());
		detailVo.setStatus(product.getStatus());
		detailVo.setStock(product.getStock());
		
		//imageHost
		//获取图片地址，这里使用了配置文件，方便统一修改、与代码分离、热部署
		detailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/"));
		//parentCategoryId
		Category category =  categoryMapper.selectByPrimaryKey(product.getCategoryId());
		if(category == null) {
			detailVo.setParentCategoryId(0);	//默认根节点
		}else {
			detailVo.setParentCategoryId(category.getParentId());
		}
		//createTime
		detailVo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
		//updateTime
		detailVo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));
		
		return detailVo;
	}
	
	//查询所有，带分页
	@Override
	public ServerResponse<PageInfo> getProductList(int pageNum, int pageSize) {
		log.info("saveOrUpdateProduct.getProductList");
		//1.startPage--statr
		//2.填充自己的sql逻辑
		//3.pageHelper收尾

		PageHelper.startPage(pageNum, pageSize);
		List<Product> productList = productMapper.selectList();
		List<ProductListVo> productVoList = Lists.newArrayList();
		//循环填充至vo
		for (Product productItem : productList) {
			ProductListVo productListVo = assembleProductListVo(productItem);
			//把vo放入list里
			productVoList.add(productListVo);
		}
		//分页
		PageInfo pageResult = new PageInfo(productList);
		pageResult.setList(productVoList);
		return ServerResponse.createBySuccess(pageResult);
	}
	
	//组装vo
	private ProductListVo assembleProductListVo(Product product) {
		ProductListVo productListVo = new ProductListVo();
		
		productListVo.setId(product.getId());
		productListVo.setName(product.getName());
		productListVo.setCategoryId(product.getCategoryId());
		productListVo.setMainImage(product.getMainImage());
		productListVo.setPrice(product.getPrice());
		productListVo.setSubtitle(product.getSubtitle());
		productListVo.setStatus(product.getStatus());
		//获取图片地址，这里使用了配置文件，方便统一修改、与代码分离、热部署
		productListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/"));
		
		return productListVo;
	}

	//搜索功能
	@Override
	public ServerResponse<PageInfo> searchProduct(String productName, Integer productId, int pageNum, int pageSize) {
		log.info("saveOrUpdateProduct.searchProduct");
		PageHelper.startPage(pageNum, pageSize);
		if(StringUtils.isNotBlank(productName)) {
			//构建sql模糊查询
			productName = new StringBuilder().append("%").append(productName).append("%").toString();
		}
		List<Product> productList = productMapper.selectByNameAndProductId(productName, productId);
		List<ProductListVo> productVoList = Lists.newArrayList();
		//循环填充至vo
		for (Product productItem : productList) {
			ProductListVo productListVo = assembleProductListVo(productItem);
			//把vo放入list中
			productVoList.add(productListVo);
		}
		//分页
		PageInfo pageResult = new PageInfo(productList);
		pageResult.setList(productVoList);
		return ServerResponse.createBySuccess(pageResult);
	}
	
}
